package com.hua.server.oauth.strategy.impl;

import com.hua.server.oauth.strategy.AuthorizationServerConfigurerStrategy;
import com.hua.server.oauth.strategy.TypeAuthorizationServerHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * jdbc 实现
 *
 * @author 华云龙
 * @date 2019-5-27
 */
@Configuration
@TypeAuthorizationServerHandler("jdbc")
@ConditionalOnClass(DataSource.class)
public class JdbcAuthorizationServerConfigStrategy implements AuthorizationServerConfigurerStrategy {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public TokenStore tokenJdbcStore() {
        /// 基于jdbc实现,令牌保存在数据库
        return new JdbcTokenStore(dataSource());
    }

    @Bean
    public ClientDetailsService clientJdbcDetailsService() {
        /// clients 基于jdbc配置
        return new JdbcClientDetailsService(dataSource());
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients, PasswordEncoder passwordEncoder) throws Exception {
        clients.withClientDetails(clientJdbcDetailsService());
    }

    @Override
    public TokenStore configure(AuthorizationServerEndpointsConfigurer endpoints) {
        return tokenJdbcStore();
    }
}
